package task

import (
	"encoding/json"

	"strconv"
	"tushare/model/aliyun/ecs"
	"tushare/model/task"

	"tushare/common"

	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon"
)

type Task struct{}

func (t Task) CreateUserTask(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)
	taskType := c.Query("taskType")
	taskRemark := c.Query("taskRemark")
	instanceId := c.Query("instance_id")
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)

	appInfo := ecs.AliyunEcsAppByUserIdAndAppName(userInfo.Id, id)
	if appInfo.Status != 0 {
		c.JSON(200, gin.H{"code": 1, "message": "应用已安装无须再安装"})
		return
	}

	ecsInfo := ecs.AliyunEcsByUserIdAndInstanceId(userInfo.Id, instanceId)

	taskJsonMap := make(map[string]interface{})
	taskJsonMap["instance_id"] = instanceId
	taskJsonMap["ip"] = ecsInfo.Ip
	taskJsonMap["ecs_app_id"] = appInfo.Id

	taskJson, _ := json.Marshal(taskJsonMap)

	userTask := task.UserTask{}
	userTask.CreateTime = carbon.Now().ToDateTimeString()
	userTask.UserId = userInfo.Id
	userTask.Status = 0
	userTask.TaskType = taskType
	userTask.TaskRemark = taskRemark
	userTask.TaskJson = string(taskJson)
	task.UserTaskCreate(userTask)

	appInfo.Status = 2
	ecs.AliyunEcsAppUpdate(id, appInfo)

	c.JSON(200, gin.H{"code": 0, "message": "成功"})
}
